<script setup>
import { defineProps, ref, onMounted, computed } from 'vue';
import { getArticleComments, likeArticle } from '@/api/article';
// 导入默认头像 - 使用已有的头像作为默认
import defaultAvatar from '@/assets/home/avatar1.jpg';
// 导入评论列表组件
import CommentsList from './CommentsList.vue';

const props = defineProps({
  post: {
    type: Object,
    required: true
  },
  users: {
    type: Object,
    required: true
  },
  categories: {
    type: Array,
    required: true
  }
});

const isLikeLoading = ref(false);
const comments = ref([]);
const isLoadingComments = ref(false);
const commentsError = ref(null);
// 控制评论区域显示
const showComments = ref(false);
// 控制内容展开/折叠状态
const isContentExpanded = ref(false);

// 作者信息计算属性
const authorInfo = computed(() => {
  // 检查是否有原始数据中的作者信息
  if (props.post.originalData) {
    const { firstName, lastName, avatarUrl, nickname, username } = props.post.originalData;
    
    // 创建作者名称，按优先级使用：nickname > firstName+lastName > username > userId
    let name = '';
    if (nickname) {
      name = nickname;
    } else if (firstName || lastName) {
      name = [firstName, lastName].filter(Boolean).join(' ');
    } else if (username) {
      name = username;
    } else {
      name = `用户${props.post.author}`;
    }
    
    // 创建作者头像URL，如果avatarUrl不存在或无效，使用默认头像
    // 注意：有时候后端可能返回空字符串或"null"字符串
    const avatar = avatarUrl && avatarUrl !== 'null' && avatarUrl !== '' 
      ? avatarUrl 
      : getDefaultAvatar(props.post.author);
    
    // 返回作者信息
    return { name, avatar };
  }
  
  // 如果没有原始数据，则尝试从users对象获取
  const userId = props.post.author;
  const userKey = typeof userId === 'string' ? userId : `user${userId}`;
  
  if (props.users && (props.users[userKey] || props.users[`user${userId}`] || props.users[`user_${userId}`])) {
    // 尝试几种可能的key格式
    const userInfo = props.users[userKey] || props.users[`user${userId}`] || props.users[`user_${userId}`];
    return userInfo;
  }
  
  // 如果都没有，返回默认值
  return {
    name: `用户${userId}`,
    avatar: getDefaultAvatar(userId)
  };
});

// 获取默认头像的辅助函数
const getDefaultAvatar = (userId) => {
  // 如果有导入的默认头像，则使用它
  if (defaultAvatar) {
    return defaultAvatar;
  }
  // 否则使用占位符
  return 'https://via.placeholder.com/40';
};

// 获取文章评论
const fetchComments = async () => {
  // 如果评论区尚未显示，不加载评论数据
  if (!showComments.value) return;

  // 验证文章ID是否有效
  if (!props.post || !props.post.id) {
    console.warn('文章ID无效，无法获取评论');
    return;
  }
  
  isLoadingComments.value = true;
  commentsError.value = null;
  
  try {
    const response = await getArticleComments(props.post.id);
    
    // 检查响应数据格式
    if (response && response.data) {
      if (Array.isArray(response.data)) {
        comments.value = response.data;
      } else if (response.data.list && Array.isArray(response.data.list)) {
        comments.value = response.data.list;
      } else if (response.data.comments && Array.isArray(response.data.comments)) {
        comments.value = response.data.comments;
      } else if (response.data.data && Array.isArray(response.data.data)) {
        comments.value = response.data.data;
      } else {
        console.warn('评论数据格式不正确，使用空数组');
        comments.value = [];
      }
    } else {
      comments.value = [];
    }
    
    // 更新评论数量 - 使用安全的方式更新
    if (props.post) {
      props.post.comments = comments.value.length;
    }
  } catch (error) {
    console.error('获取评论失败:', error);
    commentsError.value = '获取评论数据失败，请稍后再试';
    comments.value = []; // 确保在错误情况下设置为空数组
  } finally {
    isLoadingComments.value = false;
  }
};

// 点赞功能
const likePost = async () => {
  if (isLikeLoading.value || !props.post || !props.post.id) return;
  
  isLikeLoading.value = true;
  
  try {
    await likeArticle(props.post.id);
    
    // 确保post对象存在后再更新属性
    if (props.post) {
      props.post.likes = (props.post.likes || 0) + 1;
    }
    
    // 添加点赞动画效果
    const likeButton = document.querySelector(`.like-button-${props.post.id}`);
    if (likeButton) {
      likeButton.classList.add('liked');
      setTimeout(() => {
        likeButton.classList.remove('liked');
      }, 1000);
    }
  } catch (error) {
    console.error('点赞失败:', error);
  } finally {
    isLikeLoading.value = false;
  }
};

// 切换评论区域显示
const toggleComments = () => {
  // 只切换评论区显示状态，不涉及评论发布功能
  showComments.value = !showComments.value;
  
  // 如果打开评论区并且还没有加载过评论，则加载评论
  if (showComments.value && comments.value.length === 0 && !commentsError.value) {
    fetchComments();
  }
};

// 切换内容展开/折叠状态
const toggleContent = () => {
  isContentExpanded.value = !isContentExpanded.value;
};

// 处理富文本内容安全截取
const getFormattedContent = computed(() => {
  if (!props.post.content) return '';
  
  // 如果内容已展开或内容少于150个字符，直接返回完整内容
  if (isContentExpanded.value || props.post.content.length <= 150) {
    return props.post.content;
  }
  
  // 创建临时div解析HTML内容
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = props.post.content;
  
  // 获取纯文本内容长度
  const textContent = tempDiv.textContent || tempDiv.innerText;
  if (textContent.length <= 150) {
    return props.post.content;
  }
  
  // 如果内容超长，尝试安全截取
  // 创建新临时div用于截取
  const truncDiv = document.createElement('div');
  truncDiv.innerHTML = props.post.content;
  
  // 获取所有子节点
  const allNodes = [];
  const getNodes = (node) => {
    if (node.nodeType === 3) { // 文本节点
      allNodes.push(node);
    } else if (node.nodeType === 1) { // 元素节点
      Array.from(node.childNodes).forEach(child => getNodes(child));
    }
  };
  
  Array.from(truncDiv.childNodes).forEach(node => getNodes(node));
  
  // 计算总长度并截取
  let totalLength = 0;
  let truncated = false;
  
  for (const node of allNodes) {
    const nodeText = node.textContent || node.nodeValue || '';
    if (totalLength + nodeText.length > 150) {
      // 计算剩余可取字符数
      const remainingLength = 150 - totalLength;
      if (remainingLength > 0) {
        node.textContent = nodeText.substring(0, remainingLength) + '...';
      } else {
        node.textContent = '';
      }
      truncated = true;
      break;
    }
    totalLength += nodeText.length;
  }
  
  // 如果截取了内容，移除截取点之后的所有节点
  if (truncated) {
    const seenNodes = new Set();
    for (const node of allNodes) {
      seenNodes.add(node);
      if (node.textContent && node.textContent.includes('...')) {
        // 移除该节点后的所有兄弟节点
        let current = node.nextSibling;
        while (current) {
          const next = current.nextSibling;
          if (!seenNodes.has(current) && current.parentNode) {
            current.parentNode.removeChild(current);
          }
          current = next;
        }
        
        // 向上查找父节点并移除之后的兄弟节点
        let parent = node.parentNode;
        while (parent && parent !== truncDiv) {
          let current = parent.nextSibling;
          while (current) {
            const next = current.nextSibling;
            if (current.parentNode) {
              current.parentNode.removeChild(current);
            }
            current = next;
          }
          parent = parent.parentNode;
        }
        break;
      }
    }
  }
  
  return truncDiv.innerHTML;
});

// 检查内容是否需要折叠
const shouldShowExpandButton = computed(() => {
  if (!props.post.content) return false;
  
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = props.post.content;
  const textContent = tempDiv.textContent || tempDiv.innerText;
  
  return textContent.length > 150;
});

onMounted(() => {
  // 组件挂载时不自动获取评论数据，而是等用户点击时再加载
});
</script>

<template>
  <div 
    class="post-card"
    :class="{ 'pinned': post.pinned }"
  >
    <div class="post-header">
      <div class="post-author">
        <div class="author-avatar">
          <img 
            :src="authorInfo.avatar"
            :alt="authorInfo.name"
            class="avatar-img"
            @error="$event.target.src = defaultAvatar || 'https://via.placeholder.com/40'"
            loading="lazy"
          >
        </div>
        <div class="author-info">
          <h4 class="author-name">{{ authorInfo.name }}</h4>
        </div>
      </div>
      <div class="post-meta">
        <span class="post-date">{{ post.date || '未知日期' }}</span>
        <span v-if="post.pinned" class="post-pinned-badge">📌 置顶</span>
      </div>
    </div>
    
    <div class="post-content">
      <h3 class="post-title">{{ post.title || '无标题' }}</h3>
      <div v-if="post.content" class="post-excerpt rich-content" v-html="getFormattedContent"></div>
      <p v-else class="post-excerpt">无内容</p>
      
      <!-- 展开/折叠按钮 -->
      <button 
        v-if="shouldShowExpandButton" 
        class="expand-button"
        @click="toggleContent"
      >
        {{ isContentExpanded ? '收起内容' : '展开阅读全文' }}
      </button>
    </div>
    
    <div class="post-footer">
      <div class="post-category">
        <span class="category-icon">
          {{ categories.find(c => c.id === post.category)?.icon || '📂' }}
        </span>
        <span class="category-name">
          {{ categories.find(c => c.id === post.category)?.name || '未分类' }}
        </span>
      </div>
      
      <div class="post-stats">
        <div class="stat-item like-stat">
          <button 
            :class="`like-button-${post.id}`" 
            class="like-button" 
            @click="likePost"
            :disabled="isLikeLoading"
          >
            <span class="like-icon">❤️</span>
            <span class="like-count">{{ post.likes || 0 }}</span>
          </button>
        </div>
        <div class="stat-item">
          <button 
            class="comment-button" 
            @click="toggleComments"
            :title="showComments ? '收起评论' : '查看评论'"
          >
            <span class="stat-icon">💬</span>
            <span class="stat-count">
              <template v-if="isLoadingComments && !showComments">...</template>
              <template v-else>{{ post.comments || 0 }}</template>
            </span>
          </button>
        </div>
        <div class="stat-item">
          <span class="stat-icon">👁️</span>
          <span class="stat-count">{{ post.views || 0 }}</span>
        </div>
      </div>
    </div>
    
    <!-- 评论区域 -->
    <div v-if="showComments" class="comments-section">
      <CommentsList 
        :comments="comments"
        :articleId="post.id"
        :isLoading="isLoadingComments"
        @refresh-comments="fetchComments"
      />
    </div>
    
    <!-- 评论加载错误提示 -->
    <div v-if="commentsError" class="comments-error">
      {{ commentsError }}
    </div>
  </div>
</template>

<style scoped>
/* 帖子卡片样式 */
.post-card {
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  padding: 25px;
  transition: all 0.3s;
  border: 1px solid #f0f0f0;
  opacity: 0;
  transform: translateY(20px);
  animation: fadeInUp 0.5s forwards;
}

.post-card:hover {
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
  transform: translateY(-3px);
}

.post-card.pinned {
  border-left: 4px solid #00c389;
  background-color: #f9fffe;
}

.post-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.post-author {
  display: flex;
  align-items: center;
}

.author-avatar {
  width: 40px;
  height: 40px;
  margin-right: 12px;
  border-radius: 50%;
  overflow: hidden;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.author-name {
  font-size: 1rem;
  color: #333;
  margin: 0 0 3px;
}

.post-meta {
  display: flex;
  align-items: center;
}

.post-date {
  color: #888;
  font-size: 0.9rem;
}

.post-pinned-badge {
  display: flex;
  align-items: center;
  margin-left: 10px;
  padding: 3px 8px;
  background-color: #f2fbfa;
  color: #00c389;
  border-radius: 4px;
  font-size: 0.85rem;
  font-weight: 500;
}

.post-content {
  margin-bottom: 20px;
}

.post-title {
  font-size: 1.25rem;
  color: #333;
  margin: 0 0 10px;
  font-weight: 600;
}

.post-excerpt {
  color: #666;
  line-height: 1.5;
  font-size: 1rem;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
}

.post-category {
  display: flex;
  align-items: center;
  padding: 5px 12px;
  background-color: #f8f8f8;
  border-radius: 5px;
}

.post-stats {
  display: flex;
  gap: 15px;
}

.like-button {
  display: flex;
  align-items: center;
  background: none;
  border: none;
  padding: 0;
  cursor: pointer;
  transition: all 0.3s;
}

.like-button.liked .like-icon {
  animation: heartBeat 1s;
}

.like-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.like-icon {
  font-size: 1.1rem;
  margin-right: 5px;
}

.comment-button {
  display: flex;
  align-items: center;
  background: none;
  border: none;
  padding: 0;
  cursor: pointer;
  transition: all 0.3s;
}

.comment-button:hover {
  color: #00c389;
}

.comments-section {
  margin-top: 15px;
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.comments-error {
  color: #e74c3c;
  font-size: 0.9rem;
  margin-top: 10px;
  padding: 8px;
  background-color: #fef2f2;
  border-radius: 5px;
  text-align: center;
}

@keyframes fadeInUp {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes heartBeat {
  0% {
    transform: scale(1);
  }
  14% {
    transform: scale(1.3);
  }
  28% {
    transform: scale(1);
  }
  42% {
    transform: scale(1.3);
  }
  70% {
    transform: scale(1);
  }
}

@media (max-width: 768px) {
  .post-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .post-meta {
    justify-content: flex-end;
  }
}

@media (max-width: 576px) {
  .post-footer {
    flex-direction: column;
    gap: 15px;
  }
  
  .post-stats {
    width: 100%;
    justify-content: space-between;
  }
}

/* 富文本内容样式 */
.rich-content {
  overflow: hidden;
}

.rich-content :deep(img) {
  max-width: 100%;
  max-height: 500px; /* 限制图片最大高度 */
  height: auto;
  border-radius: 4px;
  margin: 8px 0;
  object-fit: contain; /* 保持图片比例 */
}

.rich-content :deep(a) {
  color: #00c389;
  text-decoration: none;
}

.rich-content :deep(a:hover) {
  text-decoration: underline;
}

.rich-content :deep(p) {
  margin: 0.5em 0;
}

.rich-content :deep(ul), .rich-content :deep(ol) {
  padding-left: 20px;
  margin: 0.5em 0;
}

.rich-content :deep(blockquote) {
  border-left: 4px solid #e0e0e0;
  padding-left: 16px;
  margin: 0.5em 0;
  color: #777;
}

.rich-content :deep(h1), .rich-content :deep(h2), .rich-content :deep(h3), 
.rich-content :deep(h4), .rich-content :deep(h5), .rich-content :deep(h6) {
  margin: 0.5em 0;
  color: #333;
}

/* 折叠/展开按钮样式 */
.expand-button {
  display: inline-block;
  margin-top: 10px;
  padding: 5px 15px;
  background-color: #f8f8f8;
  color: #00c389;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.3s;
}

.expand-button:hover {
  background-color: #00c389;
  color: white;
  border-color: #00c389;
}
</style> 